package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.Constants;
import com.zzyl.dto.UserDto;
import com.zzyl.entity.User;
import com.zzyl.entity.UserRole;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.DeptMapper;
import com.zzyl.mapper.UserMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.UserService;
import com.zzyl.utils.NoProcessing;
import com.zzyl.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Set;

import static com.zzyl.enums.BasicEnum.USER_LOCATED_BOTTOMED_DEPT;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private DeptMapper deptMapper;

    @Override
    @Transactional
    public void addUser(UserDto userDto) {
        User user = BeanUtil.toBean(userDto, User.class);
        //判断是否添加到最底层部门
        int lowestDept = deptMapper.isLowestDept(user.getDeptNo());
        if (lowestDept == 0) {
            throw new BaseException(BasicEnum.USER_LOCATED_BOTTOMED_DEPT);
        }
        //密码加密
        String password = user.getPassword();
        user.setPassword(BCrypt.hashpw(password, BCrypt.gensalt()));
        Set<String> roleVoIds = userDto.getRoleVoIds();
        userMapper.insert(user);
        for (String roleVoId : roleVoIds) {
            UserRole userRole = UserRole.builder().userId(user.getId()).roleId(Long.valueOf(roleVoId)).build();
            userRoleMapper.insert(userRole);
        }
    }

    @Override
    public PageResponse<UserVo> getUserPage(UserDto userDto, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        String deptNo = userDto.getDeptNo();
        if(deptNo!=null){
            userDto.setDeptNo(NoProcessing.processString(deptNo));
        }
        Page<UserVo>page= userMapper.page(userDto);
        for (UserVo userVo : page) {
            Set<String> roleVoIds=userRoleMapper.selectRoleVoIdByUserId(userVo.getId());
            Set<String> roleLabels=userRoleMapper.selectRoleLableByUserId(userVo.getId());
            userVo.setRoleVoIds(roleVoIds);
            userVo.setRoleLabels(roleLabels);
        }
       return PageResponse.of(page,UserVo.class);
    }
}
